<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-row :gutter="20">
						<a-col style="padding: 0 5px;" :span="6">
							<a-form-item label="选择供应商名称">
								<a-select v-model:value="searchState.parent_id" :show-search="true" placeholder="选择供应商名称" :options="supplierOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="项目">
								<a-select v-model:value="searchState.department_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="委托人">
								<a-input v-model:value="searchState.fullname" placeholder="请选择委托人" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="手机号">
								<a-input v-model:value="searchState.mobile" placeholder="请输入手机号" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="状态">
								<a-select v-model:value="searchState.status" placeholder="请选择状态" :options="statusOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="4">
							<a-space>
								<a-button type="primary" html-type="submit">
									<search-outlined />搜索
								</a-button>
								<a-button v-permission="204" type="primary" danger @click="router.push('consignor/create')">
									<plus-outlined />新增委托人
								</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
			<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="sources" :pagination="pagination" :loading="loading" @change="initData">
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'fullname'">
						<span>
							<a-badge :status="record.status === 1 ? 'success' : 'error'" />
							<a-tooltip placement="topLeft" :title="record.fullname">
								{{ record.fullname }}
							</a-tooltip>
						</span>
					</template>
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button v-permission="206" type="link" @click="router.push(`/consignor/detail/${record.id}`)">
								<diff-outlined />查看
							</a-button>
							<a-button v-permission="205" type="link" @click="editManuallySignedPic(record)">>
								<edit-outlined />签名
							</a-button>
							<template v-if="![0,1,2].includes(record.workflow_status)">
								<a-button v-permission="205" type="link" @click="router.push(`consignor/edit/${record.id}`)">
									<edit-outlined />修改
								</a-button>
								<a-button v-permission="207" type="link" style="color:#ff7875" @click="deleteUser(record.id)">
									<delete-outlined />删除
								</a-button>
							</template>
						</a-space>
					</template>
					<template v-if="column.dataIndex === 'manually_signed_file_path'">
						<span v-if="record['manually_signed_file_path']">
							<a-image :width="60" :src="record['manually_signed_file_path'][0].url || record['manually_signed_file_path']" />
						</span>
					</template>
					<template v-else-if="column.dataIndex === 'departments'">
						<span
							v-for="(d, index) in record['departments']"
							:key="index"
							:class="{
								success: dayjs(d.UserDepartment?.start_validity).format('YYYY/MM/DD') <= dayjs().format('YYYY/MM/DD') && dayjs(d.UserDepartment?.end_validity).format('YYYY/MM/DD') >= dayjs().format('YYYY/MM/DD'),
								disabled: dayjs(d.UserDepartment?.start_validity).format('YYYY/MM/DD') > dayjs().format('YYYY/MM/DD') || dayjs(d.UserDepartment?.end_validity).format('YYYY/MM/DD') < dayjs().format('YYYY/MM/DD'),
								error: !d.UserDepartment?.start_validity || !d.UserDepartment?.end_validity || !d.UserDepartment?.entrust_file_path
							}"
						>
							{{ d.name }} ({{ dayjs(d.UserDepartment?.start_validity).format('YYYY/MM/DD') }} ~ {{ dayjs(d.UserDepartment?.end_validity).format('YYYY/MM/DD') }})<br />
						</span>
					</template>
				</template>
			</a-table>
			<a-modal v-model:visible="manuallySignedVisible" width="600px" title="签名照片" @ok="saveUserManuallySigned">
				<a-form ref="manuallySigned" :model="manuallySignedFormState" v-bind="{ labelCol: { style: { width: '100px' } } }">
					<a-form-item label="签名照片" name="file_path" :rules="{ required: true, message: '请上传签名照片' }">
						<a-upload v-model:file-list="manuallySignedFormState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeClientUpload" @change="changeClientUpload">
							<a-button>
								<template v-if="manuallySignedFormState.uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传照片
								</template>
							</a-button>
						</a-upload>
						<span style="color:#ccc">
							提交签名照片
							<span style="color:red">JPG,PNG</span>文件, 尺寸不能超过<span style="color:red">135*60px</span>
						</span>
					</a-form-item>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>
<script setup>
import { computed, getCurrentInstance, onMounted, reactive, ref } from "vue";
import { post } from "@/utils/index.js";
import { usePagination } from "vue-request";
import {
	DeleteOutlined,
	DiffOutlined,
	EditOutlined, ImportOutlined,
	LoadingOutlined,
	PlusOutlined,
	SearchOutlined
} from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { baseURL } from "@/utils/request.js";
import dayjs from "dayjs";
const { proxy } = getCurrentInstance();
const router = useRouter();
const searchRef = ref();
const searchState = reactive({
	is_consignor: 1,
});
const manuallySigned = ref();
const manuallySignedFormState = ref({});
const manuallySignedVisible = ref(false);
const projectOptions = ref([]);
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	{
		title: "委托人名称",
		dataIndex: "fullname",
		sorter: false,
		width: 220,
		ellipsis: true,
	},
	{
		title: "供应商名称",
		dataIndex: "parent_user",
		sorter: false,
		width: 220,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.company_name;
		}
	},
	{
		title: "绑定项目",
		dataIndex: "departments",
		sorter: false,
		ellipsis: true,
		// customRender: ({ text, record, index, column }) => {
		// 	let date = '';
		// 	for (const d of text) {
		// 		date += `${d.name}(${dayjs(d.UserDepartment?.start_validity).format('YYYY/MM/DD')}~${dayjs(d.UserDepartment?.end_validity).format('YYYY/MM/DD')})<br/>`
		// 	}
		// 	return <div>111</div>;
		// }
	},
	{
		title: "委托人签名",
		dataIndex: "manually_signed_file_path",
		sorter: false,
		ellipsis: true
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 240,
		align: "center"
	}
];
const statusOptions = [
	{
		value: 1,
		label: "正常"
	},
	{
		value: 0,
		label: "冻结"
	}
];
post("department/projects?type=3").then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
});
const supplierOptions = ref([]);
const sources = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 680
}));
const getSupplierOptions = async () => {
	const result = await post("user", { is_supplier: 1, page_size: Infinity })
	supplierOptions.value = result.data.map(d => {
		return {
			value: d.id,
			label: d.company_name || d.mobile,
		};
	});
}
getSupplierOptions();
const { data, loading, run, current, pageSize, total } = usePagination(async params => post("user", { ...params, ...searchState }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));
const route = useRoute();
const query = route.query;
const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.parent_id) searchState.parent_id = parseInt(query.parent_id);
	if (query.department_id) searchState.department_id = parseInt(query.department_id);
	if (query.fullname) searchState.fullname = query.fullname;
	if (query.mobile) searchState.mobile = query.mobile;
	if (query.status) searchState.status = parseInt(query.status);
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const deleteUser = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的委托人吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("user/delete", { id }).then(() => {
				proxy.$message.success("委托人删除成功");
				initData();
			});
		}
	});
};
const editManuallySignedPic = (record) => {
	manuallySignedVisible.value = true;
	let file_path = [];
	if (record.manually_signed_file_path) {
		try {
			file_path = JSON.parse(record.manually_signed_file_path);
		} catch (e) {
			file_path.push({
				name: '签名照片',
				url: record.manually_signed_file_path,
			})
		}
	}
	manuallySignedFormState.value = {
		id: record.id,
		file_path
	};
}
//上传前校验
const beforeClientUpload = file => {
	manuallySignedFormState.value.uploading = true;
	if (!['image/png', 'image/jpeg'].includes(file.type)) {
		proxy.$message.error("只能上传照片或PDF文件");
		manuallySignedFormState.value.uploading = false;
		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		manuallySignedFormState.value.uploading = false;
		return false;
	}
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = (e) => {
			const img = new Image();
			img.onload = () => {
				const width = img.width;
				const height = img.height;
				if (parseFloat(width) > 135 || parseFloat(height) > 60) {
					manuallySignedFormState.value.uploading = false;
					proxy.$message.error("上传图片尺寸不能超过135*60px");
					reject(false);
				}
				resolve();
			};
			img.onerror = reject;
			img.src = e.target.result;
		};
		reader.readAsDataURL(file);
	});
};
const changeClientUpload = ({ file }) => {
	if (file.status === "done") {
		manuallySignedFormState.value.file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		manuallySignedFormState.value.uploading = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		manuallySignedFormState.value.file_path = manuallySignedFormState.value.file_path.filter((item) => item.url)
	}
};
function saveUserManuallySigned() {
	manuallySigned.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			if (!manuallySignedFormState.value.file_path[0].url) {
				return proxy.$message.error('请上传附件');
			}
			const params = { ...manuallySignedFormState.value };
			params.file_path = params.file_path[0].url;
			post('user/saveManuallySignedPic', params).then(() => {
				proxy.$message.success('提交成功', 1);
				manuallySignedVisible.value = false;
				initData()
			}).catch((err) => {
				proxy.$message.error(err);
			});
		})
		.catch(err => {

		});
}
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
  height: calc(100vh - 170px);
}
.success {
  color: #0d9424;
}
.disabled {
  color: #ccc;
}
.error {
  color: red;
}
</style>